<template>
  <div>
    <Card class="search-condition">
      <Row>
        <span>赛事名称：</span>
        <Input v-model="pageModel.eventsName" placeholder="请输入" clearable style="width: 150px" />
        <span>赛事年度：</span>
        <DatePicker v-model="pageModel.niandu" type="year" placeholder="请选择" clearable style="width: 150px"></DatePicker>
        <span>赛事状态：</span>
        <dict model="pageModel.competitionState" :value="pageModel.competitionState" @click="getVal" code="ZGX_SSZTSX"></dict>
        <span>赛事进度：</span>
        <dict model="pageModel.gameState" :value="pageModel.gameState" @click="getVal" code="ZGX_BSZT"></dict>
        <span>承办单位：</span>
        <Select v-model="pageModel.undertakingUnit" placeholder="请选择" style="width:130px;" clearable>
          <Option v-for="(_item,index) in units" :key="index" :value="_item.teamId">{{_item.teamName}}</Option>
        </Select>
        <span>赛事级别：</span>
        <dict model="pageModel.gradeCode" :value="pageModel.gradeCode" @click="getVal" code="ZGX_BSJB" :parentCode="kindCode"></dict>
        <span v-if="['5','6','7','8'].includes(kindCode)">赛事类型：</span>
        <dict v-if="['5','6','7','8'].includes(kindCode)" model="pageModel.youthEventsType" :value="pageModel.youthEventsType" @click="getVal" code="ZGX_QSNBSLX"></dict>
        <Button @click="fetchListStart" class="m-l-sm" type="primary" icon="md-search">筛选</Button>
        <Button @click="reset" class="m-l-sm" icon="md-sync">重置</Button>
      </Row>
    </Card>
    <Row class="m-b-sm m-t-sm">
      <Button @click="addGame" type="primary" icon="md-add">创建赛事</Button>
    </Row>
    <Card>
      <Row>
        <Table :loading="loading" stripe border :columns="tableColumns" :data="tableData"></Table>
        <page-temp :total="total" :current="page.pageNo" :size="page.pageSize" @changePage='changePage'></page-temp>
      </Row>
    </Card>
    <Modal v-model="visible" width='800' :mask-closable="false" :closable="false" title="提交审核">
      <Card>
        <Row>
          <Col span="17" offset="3">
          <Form ref="verify" :model="verify" :rules="rules" :label-width="120">
            <Row>
              <Col>
              <FormItem prop="verifyExplain" style="width:100%;" label="请填写提交说明">
                <Input v-model="verify.verifyExplain" type="textarea" :rows="4" placeholder="请输入" />
              </FormItem>
              </Col>
            </Row>
          </Form>
          </Col>
        </Row>

      </Card>
      <div slot="footer">
        <Button @click="cancel">取消</Button>
        <Button @click="apply" class="m-l-md" type="primary">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import dict from "_c/dict/dict.vue";
import dictSpan from "_c/dict/dict-span.vue";
import Api from "@/api/game";
import ApiApply from "@/api/game-apply";
import { getDict, check } from "@/api/configure";
const api = new Api();
const apiApply = new ApiApply();
// 赛事管理
export default {
  props: ["kindCode"],
  components: {
    dict,
    dictSpan
  },
  data() {
    return {
      loading: true,
      access: this.$store.state.user.access,
      units: [],
      total: 0,
      visible: false,
      pageModel: {
        niandu: null,
        eventsName: null,
        competitionState: null,
        gameState: null,
        undertakingUnit: null,
        youthEventsType: null
      },
      page: {
        pageSize: this.$config.PAGE_SIZE,
        pageNo: 1,
        kindCode: this.kindCode
      },
      kindNameUrl: this.$config.kindNameUrl(this.kindCode),
      tableColumns: [],
      tableColumnsArr: [
        {
          title: "序号",
          width: 65,
          align: "left",
          render: (h, params) => {
            return h(
              "span",
              this.page.pageSize * (this.page.pageNo - 1) + params.index + 1
            );
          }
        },
        {
          title: "赛事名称",
          key: "eventsName",
          align: "left",
          render: (h, params) => {
            let self = this;
            let title = self.$config.userName(
              params.row.eventsName,
              params.row.eventsEnglishName
            );
            return h(
              "a",
              {
                on: {
                  click: () => {
                    let self = this;
                    if (self.access.includes("GAME_MANAGE")) {
                      self.$router.push({
                        path:
                          "/game-management/" +
                          self.kindNameUrl +
                          params.row.eventsId
                      });
                    } else {
                      if (params.row.applyId) {
                        self.$router.push({
                          path:
                            "/game-apply-management/match/" + params.row.applyId
                        });
                      } else {
                        self.$router.push({
                          path:
                            "/game-management/" +
                            self.kindNameUrl +
                            params.row.eventsId
                        });
                      }
                    }
                  }
                },
                domProps: {
                  title
                }
              },
              title
            );
          }
        },
        {
          title: "赛事年度",
          key: "niandu",
          align: "left",
          width: 85
        },
        {
          title: "赛事级别",
          key: "gradeCode",
          align: "left",
          width: 85,
          ellipsis: true,
          render: (h, params) => {
            return h(dictSpan, {
              props: {
                code: "ZGX_BSJB",
                parentCode: params.row.kindCode,
                value: params.row.gradeCode
              }
            });
          }
        },
        {
          title: "赛事时间",
          key: "startTime",
          align: "left",
          // width:185,
          // ellipsis: true,
          render: (h, params) => {
            let self = this;
            let title = self.$config.getDate(
              params.row.startTime,
              params.row.endTime
            );
            return h("span", { domProps: { title } }, title);
          }
        },
        {
          title: "赛事计划",
          key: "planField",
          align: "left",
          width: 85,
          render: (h, params) => {
            return h(
              "span",
              {
                style: {
                  color: "#FF9933"
                }
              },
              (params.row.planField || 0) + "场"
            );
          }
        },
        {
          title: "赛事安排",
          key: "planArrange",
          align: "left",
          width: 85,
          render: (h, params) => {
            return h(
              "span",
              {
                style: {
                  color: "green"
                }
              },
              (params.row.planArrange || 0) + "场"
            );
          }
        },
        {
          title: "赛事状态",
          key: "competitionState",
          align: "left",
          width: 85,
          render: (h, params) => {
            return h(dictSpan, {
              props: {
                code: "ZGX_SSZTSX",
                value: params.row.competitionState,
                color: params.row.competitionState === "0" ? "green" : "red"
              }
            });
          }
        },
        {
          title: "赛事进度",
          key: "gameState",
          align: "left",
          width: 85,
          render: (h, params) => {
            return h(dictSpan, {
              props: { code: "ZGX_BSZT", value: params.row.gameState }
            });
          }
        },
        {
          title: "申请类型",
          key: "operationType",
          width: 85,
          render: (h, params) => {
            return h(dictSpan, {
              props: {
                code: "ZGX_SSCZLX",
                value: params.row.operationType
              }
            });
          }
        },
        {
          title: "审核状态",
          key: "verifyStatus",
          width: 85,
          render: (h, params) => {
            return h(dictSpan, {
              props: {
                code: "ZGX_SSSHZT",
                value: params.row.verifyStatus
              },
              class: "verify-status-" + params.row.verifyStatus
            });
          }
        },
        {
          title: "操作",
          key: "action",
          align: "left",
          width: 315,
          render: (h, params) => {
            let self = this;
            if (self.access.includes("GAME_MANAGER")) {
              return h("div", [
                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px",
                      display: params.row.verifyStatus === "0" ? "" : "none"
                    },
                    on: {
                      click: () => {
                        this.verify.verifyId = params.row.verifyId;
                        this.verify.eventsId = params.row.eventsId;
                        this.visible = true;
                      }
                    }
                  },
                  "提交审核"
                ),
                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        if (params.row.verifyStatus === null) {
                          self.$router.push({
                            path: `/game-management/edit/${params.row.kindCode}/${params.row.eventsId}`
                          });
                        } else {
                          self.$router.push({
                            path: `/game-apply-management/edit/${params.row.applyId}`
                          });
                        }
                      }
                    }
                  },
                  ["0", "3"].includes(params.row.verifyStatus) &&
                    params.row.operationType !== "3"
                    ? "编辑"
                    : "查看"
                ),
                h(
                  "Poptip",
                  {
                    props: {
                      confirm: true,
                      title: "您确定要删除这条数据吗?",
                      transfer: true
                    },
                    on: {
                      "on-ok": () => {
                        //删除数据
                        this.del(params.row);
                      }
                    }
                  },
                  [
                    h(
                      "Button",
                      {
                        style: {
                          marginRight: "5px",
                          display: ["1", "3"].includes(params.row.verifyStatus)
                            ? "none"
                            : ""
                        },
                        props: {
                          size: "small",
                          placement: "top"
                        }
                      },
                      params.row.verifyStatus === "0" ? "撤销申请" : "删除"
                    )
                  ]
                ),
                h(
                  "Button",
                  {
                    style: {
                      marginRight: "5px",
                      display: params.row.verifyStatus === "3" ? "" : "none"
                    },
                    props: {
                      size: "small"
                    },
                    on: {
                      click: () => {
                        //关闭赛事
                        this.close(params.row);
                      }
                    }
                  },
                  "关闭申请"
                ),
                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        self.$router.push({
                          path: `/game-apply-management/game-record-card/${params.row.eventsId}`
                        });
                      }
                    }
                  },
                  "查看审核记录"
                )
              ]);
            } else {
              return h("div", [
                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        self.$router.push({
                          path: `/game-management/edit-other/${self.kindCode}/${params.row.eventsId}`
                        });
                      }
                    }
                  },
                  "查看"
                ),
                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        self.copy(params.row.eventsId);
                      }
                    }
                  },
                  "赛事复制"
                ),
                h(
                  "Poptip",
                  {
                    props: {
                      confirm: true,
                      title:
                        params.row.competitionState === "0"
                          ? "失效：将不显示在用户端?"
                          : "生效：将显示在用户端?",
                      transfer: true
                    },

                    on: {
                      "on-ok": () => {
                        //删除数据
                        this.updateStatus(
                          params.row.eventsId,
                          Math.abs(params.row.competitionState - 1)
                        );
                      }
                    }
                  },
                  [
                    h(
                      "Button",
                      {
                        props: {
                          type:
                            params.row.competitionState === "0"
                              ? "error"
                              : "primary",
                          size: "small"
                        },
                        class: this.access.includes("GAME_MANAGER")
                          ? "hide"
                          : "",
                        style: {
                          marginRight: "5px"
                        }
                      },
                      params.row.competitionState === "0" ? "失效" : "生效"
                    )
                  ]
                ),
                h(
                  "Poptip",
                  {
                    props: {
                      confirm: true,
                      title: "您确定要删除这条数据吗?",
                      transfer: true
                    },
                    on: {
                      "on-ok": () => {
                        //删除数据
                        this.del(params.row);
                      }
                    }
                  },
                  [
                    h(
                      "Button",
                      {
                        style: {
                          marginRight: "5px"
                        },
                        props: {
                          size: "small",
                          placement: "top"
                        }
                      },
                      "删除"
                    )
                  ]
                )
              ]);
            }
          }
        }
      ],
      tableData: [],
      verify: { verifyStatus: 1 },
      rules: {
        verifyExplain: [
          { required: true, message: "请输入" },
          {
            max: this.$config.TAREA_SIZE,
            message: `最多输入${this.$config.TAREA_SIZE}个字符数字`
          }
        ]
      }
    };
  },
  mounted() {
    let self = this;
    if (self.access.includes("GAME_MANAGER")) {
      self.tableColumns = self.tableColumnsArr.filter(
        x => x.key !== "planArrange"
      );
    } else {
      self.tableColumns = self.tableColumnsArr.filter(
        x => !["verifyStatus", "operationType"].includes(x.key)
      );
    }
    getDict({ code: "CBDW" })
      .then(data => {
        self.units = data;
        self.fetchListStart();
      })
      .catch(error => {
        self.fetchListStart();
      });
  },
  methods: {
    // 获取字典数据
    getVal(expression) {
      let self = this;
      eval(expression);
    },
    addGame() {
      if (this.access.includes("GAME_MANAGER")) {
        this.$router.push("/game-apply-management/edit");
      } else if(this.kindCode === '10') {
        this.$router.push("/game-management/edit-other/" + this.kindCode)

      } else {
        this.$router.push("/game-management/edit/" + this.kindCode);
      }
    },
    // 获取数据
    fetchListStart() {
      let self = this;
      self.page = { ...self.page, ...self.pageModel, pageNo: 1 };
      if (self.page.niandu) {
        self.page.niandu = self.$moment(self.page.niandu).format("YYYY");
      }
      self.fetchList();
    },
    fetchList() {
      this.loading = true;
      if (this.access.includes("GAME_MANAGER")) {
        apiApply
          .listPageCompany(this.page)
          .then(data => {
            this.loading = false;
            this.tableData = data.list || [];
            this.total = data.count || 0;
          })
          .catch(error => {
            this.loading = false;
          });
      } else {
        api
          .getmatch(this.page)
          .then(data => {
            this.loading = false;
            this.tableData = data.list || [];
            this.total = data.count || 0;
          })
          .catch(error => {
            this.loading = false;
          });
      }
    },
    // 分页
    changePage(pageNum) {
      this.page.pageNo = pageNum;
      this.fetchList();
    },
    reset() {
      let self = this;
      Object.keys(self.pageModel).forEach(x => {
        self.pageModel[x] = null;
      });
      this.fetchListStart();
    },
    del(row) {
      let { eventsId, applyId, verifyStatus } = { ...row };
      // 中高协列表无verifyStatus 审核状态字段，查询获取
      let promiseCheck = null;
      if (this.access.includes("GAME_MANAGE")) {
        promiseCheck = check(eventsId);
      } else {
        promiseCheck = Promise.resolve({ verifyStatus });
      }
      promiseCheck.then(data => {
        verifyStatus = data.verifyStatus;
        let str = null;
        switch (verifyStatus) {
          case "0":
            str = "赛事公司正在处理这条赛事，请稍后处理";
            break;
          case "1":
            str = "赛事公司已对这个赛事发起申请，请前往审核当前赛事";
            break;
        }
        // 正在处理中
        if (str != null) {
          if (this.access.includes("GAME_MANAGE")) {
            this.$Message.warning({ content: str });
          } else {
            apiApply.del(applyId).then(data => {
              if (data) {
                this.fetchList();
              }
            });
          }
        } else {
          if (this.access.includes("GAME_MANAGER")) {
            let params = { eventsId, operationType: 3 };
            Object.defineProperties(params, {
              _index: {
                enumerable: false
              },
              _rowKey: {
                enumerable: false
              }
            });
            apiApply.edit(params).then(data => {
              if (data) {
                this.fetchList();
              }
            });
          } else {
            api.del({ eventsId }).then(data => {
              if (data) {
                this.fetchList();
              }
            });
          }
        }
      });
    },
    // 复制赛事
    copy(eventsId) {
      if (this.access.includes("GAME_MANAGER")) {
        api.copyApply({ eventsId }).then(data => {
          if (data) {
            this.$router.push(`/game-apply-management/edit/${data}`);
          }
        });
      } else {
        api.copy({ eventsId }).then(data => {
          if (data) {
            // this.fetchList();
            this.$router.push(
              "/game-management/edit/" + this.kindCode + "/" + data
            );
          }
        });
      }
    },
    // 赛事状态
    updateStatus(eventsId, competitionState) {
      api.updateStatus({ eventsId, competitionState }).then(data => {
        if (data) {
          this.fetchList();
        }
      });
    },
    close(row) {
      let { verifyId } = row;
      let params = { verifyId };
      apiApply.closeApply(params).then(data => {
        if (data) {
          this.fetchList();
        }
      });
    },
    // 提交申请
    apply() {
      let self = this;
      self.$refs["verify"].validate(valid => {
        if (valid) {
          self.loading = true;
          // 审核状态变为待审核
          // self.verify.verifyStatus='1';
          apiApply
            .submit(self.verify)
            .then(data => {
              self.cancel();
              this.fetchListStart();
            })
            .catch(error => {
              self.cancel();
              self.loading = false;
            });
        }
      });
    },
    // 取消提交申请
    cancel() {
      let self = this;
      self.$refs["verify"].resetFields();
      self.visible = false;
    }
  }
};
</script>

<style scoped>
</style>
